#!/usr/bin/env python3

import subprocess
import shutil
import os
import os.path
import sys
import shlex


def run_process(cmd):
    try:
        print("Running command: " + shlex.join(cmd))
        return subprocess.run(cmd, check=True, capture_output=True)
    except subprocess.CalledProcessError as e:
        print("In: " + os.getcwd(), file=sys.stderr)
        print("Command failed: " + shlex.join(cmd), file=sys.stderr)
        print("stdout output:\n" + e.stdout.decode(encoding='UTF-8',
              errors='strict'), file=sys.stderr)
        print("stderr output:\n" + e.stderr.decode(encoding='UTF-8',
              errors='strict'), file=sys.stderr)
        raise e

root = '../../../../../../../../..'

sys.path.append(root + '/ql/java/kotlin-extractor')
import kotlin_plugin_versions
defaultKotlinDependencyVersion = kotlin_plugin_versions.get_single_version()

builddir = 'build'
dependency_dir = root + '/resources/kotlin-dependencies/'
dependencies = ['kotlin-stdlib-' + defaultKotlinDependencyVersion +
                '.jar', 'kotlin-compiler-' + defaultKotlinDependencyVersion + '.jar']
classpath = ':'.join([dependency_dir + dep for dep in dependencies])
srcs = ['plugin/Plugin.kt']
output = 'plugin.jar'

if os.path.exists(builddir):
    shutil.rmtree(builddir)
os.makedirs(builddir)

run_process(['kotlinc',
            '-J-Xmx2G',
             '-d', builddir,
             '-module-name', 'test',
             '-no-reflect', '-no-stdlib',
             '-jvm-target', '1.8',
             '-classpath', classpath] + srcs)

run_process(['jar', '-c', '-f', output,
            '-C', builddir, '.',
             '-C', 'plugin/resources', 'META-INF'])
shutil.rmtree(builddir)
